<?php


namespace app\api\controller;



use app\common\lib\Snowflake;
use app\common\model\SmokeCostRecord;
use app\common\model\SmokeRecord;

use app\api\controller\AuthBase;

use think\exception\ValidateException;
use think\facade\Cache;
use think\facade\Db;
use think\facade\Log;
use function Composer\Autoload\includeFile;

class VipOrder extends AuthBase
{
    public function add(){
        $id=input('post.id');
        //拿到订单号
        $order_no = generateOrderNumber();
        $goods=Db::name('vip_goods')
            ->where('id',$id)
            ->find();
        // 启动事务
        $result['order_no'] = $order_no;
        $result['goods_id'] = $goods['id'];
        $result['user_id']=$this->userId;
        $result['price']=$goods['price'];
        $result['name']=$goods['name'];
        $result['create_time']=time();
        $result['update_time']=time();
        Db::name('vip_order')
            ->insert($result);
        Db::commit();
        return show(1, '下单成功', $order_no);
    }
    public function cancel()
    {
        $order_no = input('post.order_no');
        $receipt = input('post.transaction_receipt');
        $identifier = input('post.transaction_identifier');

            // 验证数据完整性
            if (empty($receipt) ||empty($identifier)||empty($order_no)) {
                return show(0,'请传递数据完整性');
            }

            // 获取收据数据

            // 验证收据
            $isValid = $this->verifyReceipt($receipt);
            if ($isValid) {
                // 收据验证成功，处理订单逻辑
                // 这里处理订单逻辑，例如更新订单状态、给用户增加权益等
                $order=Db::name('vip_order')
                    ->where(['order_no'=>$order_no,'status'=>0])
                    ->find();
                if (!$order){
                    return show(0,'订单查询失败');
                }
                // 示例：更新订单状态为已支付
                Db::startTrans();
                try {
                    Db::name('vip_order')
                        ->where('id',$order['id'])
                        ->update(['status'=>1,'ios_identifier'=>$identifier,'pay_time'=>time()]);
                    //增加vip记录表
                    if ($order['goods_id']==1){
                        $num=30;
                    }elseif($order['goods_id']==2){
                        $num=90;
                    }elseif($order['goods_id']==3){
                        $num=365;
                    }else{
                        // 获取2099年12月31号的日期
                        $num=99999;
                    }
                    Db::name('user_vip_record')
                        ->insert(['type'=>3,'day'=>$num,'create_time'=>time(),'user_id'=>$order['user_id']]);
                    //修改用户表
                    $user=Db::name('user')
                        ->where('id',$order['user_id'])
                        ->find();
                    if ($user['is_vip']==1){
                        if ($num==99999){
                            $vip_end_time=strtotime('2099-12-31');
                        }else{
                            $vip_end_time=$num*86400+time();
                        }
                    }else{
                        if ($num==99999){
                            $vip_end_time=strtotime('2099-12-31');
                        }else{
                            $vip_end_time=$num*86400+$user['vip_end_time'];
                        }
                    }
                    Db::name('user')
                        ->where('id',$order['user_id'])
                        ->update(['is_vip'=>2,'vip_end_time'=>$vip_end_time]);
                    //增加商品销量
                    Db::name('vip_goods')
                        ->where('id',$order['goods_id'])
                        ->inc('sales')
                        ->update();
                    Db::commit();
                    return show(1,'购买成功');
                } catch (\Exception $e) {
                    Db::rollback();
                    return show(0,$e->getMessage());
                }
            } else {
                return show(0,'订单处理失败');
            }
    }

    private function verifyReceipt($receiptData)
    {
        // 苹果生产环境验证地址
        $productionUrl = 'https://buy.itunes.apple.com/verifyReceipt';
        // 苹果沙盒环境验证地址
        $sandboxUrl = 'https://sandbox.itunes.apple.com/verifyReceipt';

        // 先尝试在生产环境验证
        $response = $this->sendRequest($productionUrl, $receiptData);
        $result = json_decode($response, true);
        if (isset($result['status']) && $result['status'] == 21007) {
            // 如果返回 21007，表示这是一个沙盒环境的收据，再尝试在沙盒环境验证
            $response = $this->sendRequest($sandboxUrl, $receiptData);
            $result = json_decode($response, true);
        }

        return isset($result['status']) && $result['status'] == 0;
    }

    private function sendRequest($url, $receiptData)
    {
        $ch = curl_init($url);
        $data = json_encode(['receipt-data' => $receiptData]);

        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);

        $response = curl_exec($ch);
        curl_close($ch);

        return $response;
    }

    /**
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 小程序唤起支付
     */
    public function go_pay()
    {
        $data = input('post.');
        $order = Db::name('vip_order')
            ->where(['order_no' => $data['order_no'], 'user_id' => $this->userId, 'status' => 0])
            ->find();
        if (!$order) {
            return $this->show(0, '对不起,当前订单状态已不能支付,请重新下单');
        }
        $user = Db::name('user')
            ->where('id', $this->userId)
            ->find();
        $goods = Db::name('vip_goods')
            ->where('id', $order['goods_id'])
            ->find();
        // 启动事务
        Db::startTrans();
        try {
            $out_trade_no = $this->order_number($user['openid']);
            Db::name('vip_order')
                ->where('id', $order['id'])
                ->update(['update_time' => time(), 'out_trade_no' => $out_trade_no]);
            $res = $this->Pay($order['price'], $user['xcx_openid'], $goods['name'], $out_trade_no);
            Db::commit();
            return show(1, '订单提交成功', $res);
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return show(0, '订单提交失败');
        }
    }
    private function order_number($openid)
    {
        //date('Ymd',time()).time().rand(10,99);//18位
        return md5($openid . time() . rand(10, 99)); //32位
    }
    /**
     * 小程序支付
     */
    public function Pay($fees, $openids, $bodys, $out_trade_nos)
    {
        $config = [
            'token' => '',
            'appid' => 'wx6cdd7b4cbeb6d004',
            'appsecret' => '016576467a74fa851b806ef9c7cd1d58',
            'encodingaeskey' => '',
            // 配置商户支付参数（可选，在使用支付功能时需要）
            'mch_id' => "1607822533",
            'mch_key' => '27f16add8345d9a76f9ca68c8e02a497',
            // 配置商户支付双向证书目录（可选，在使用退款|打款|红包时需要）
            'ssl_key' => '',
            'ssl_cer' => '',
            // 缓存目录配置（可选，需拥有读写权限）
            'cache_path' => '',
        ];


        // 创建接口实例
        $wechat = new \WeChat\Pay($config);

        // 组装参数，可以参考官方商户文档
        $options = [
            'body' => $bodys,
            'out_trade_no' => $out_trade_nos,
            'total_fee' => $fees * 100,
            'openid' => $openids,
            'trade_type' => 'JSAPI',
            'notify_url' => 'https://www.smokeji.com/wechat/pay/notify',
            'spbill_create_ip' => '82.156.114.203',
        ];

        try {

            // 生成预支付码
            $result = $wechat->createOrder($options);

            // 创建JSAPI参数签名
            $options = $wechat->createParamsForJsApi($result['prepay_id']);
            return $options;
            // @todo 把 $options 传到前端用js发起支付就可以了

        } catch (\Exception $e) {

            // 出错啦，处理下吧
            echo $e->getMessage() . PHP_EOL;
        }
    }
}
